import React, {useEffect, useMemo, useState} from 'react'
import {
	Radio,
	Space,
	Button,
	Popconfirm,
	Modal,
	Form,
	Table,
	Pagination,
	message,
} from 'antd'
import {history} from 'umi'
import {
	PlusOutlined,
	ArrowDownOutlined,
	ArrowUpOutlined,
} from '@ant-design/icons'
import moment from 'moment'
import SearchForm from '@/components/SearchForm'
// import CustomTable from '@/components/Table';
import {ClueColumns, PageType} from '../constant'
import Styles from './index.less'
import {
	clueRemove,
	getAllBdDitch,
	// getClueCount,
	getClueList,
	getKeyValueByType,
	getSubjectCompany,
} from '@/service/merchantCenter/clue'
import {getAllCitys} from '@/service/common'
import AccordingToRecordsOld from '../components/AccordingToRecordsOld'
import {downloadDocumentUrl} from '@/service/common/download'
import ExportExcl from './impoart'
import {clueAllot} from '@/service/merchantCenter/channelRule'
import Permissions from '@/components/Permissions'
import {FormSelect} from '@/components/SearchForm/SearchFormItem'

export default function List() {
	const [tabValue, setTabValue] = useState('0')
	const [count, setCount] = useState<any>({})
	const [visible, setVisible] = useState(false)
	const [visiblegj, setVisiblegj] = useState(false)
	const [citysList, setCitysList] = useState<any[]>([])
	const [form] = Form.useForm()
	const [formData, setFormData] = useState({})
	const [formItem, setFormItem] = useState()
	const [total, setTotal] = useState(0)
	const [importExcl, setImportExcl] = useState(false) // 导入弹框
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	const [tableList, setTableList] = useState<any[]>([])
	const [loading, setLoading] = useState(false)
	const [accordingToRecordsId, setAccordingToRecordsId] = useState()
	const [subjectList, setSubjectList] = useState<any[]>([])
	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
	const [selectData, setSelectData] = useState([])

	const [fleename, setFleeName] = useState([])

	const onSelectChange = (newSelectedRowKeys: React.Key[], data: any) => {
		setSelectedRowKeys(newSelectedRowKeys)
		setSelectData(data)
	}

	const getFleeNames = async (datas?: any) => {
		const data: any = datas || selectData?.[0]
		getAllBdDitch({
			subject: data?.subject,
			orgId: data?.orgId,
			cityId: data?.cityId,
		}).then((res: any) => {
			if (res.success) {
				setFleeName(res.data)
			}
		})
	}
	const [keysObj, setKeysObj] = useState([])

	useEffect(() => {
		getKeyValueByType({type: 'Follow_Status'}).then((res: any) => {
			if (res.data) {
				const obj: any = {}
				res.data.forEach((item: any) => {
					obj[item.value] = item.valueName
				})
				setKeysObj(obj)
			}
		})
	}, [])

	const getTabelValue = async (value: any, pagination?: any) => {
		setLoading(true)
		let values = value
		if (values?.date) {
			values.startDate = moment(values.date[0]).format('YYYY-MM-DD')
			values.endDate = moment(values.date[1]).format('YYYY-MM-DD')
			delete values.date
		}
		if (values?.allotDate) {
			values.allotStartDate = moment(values.allotDate[0]).format(
				'YYYY-MM-DD',
			)
			values.allotEndDate = moment(values.allotDate[1]).format(
				'YYYY-MM-DD',
			)
			delete values.allotDate
		}
		if (values?.cityId) {
			values.cityId = values?.cityId?.[1]
		}
		setFormData(values)
		const newPagination = pagination || {
			current: 1,
			size: params.size,
		}
		setParams(newPagination)
		values = {
			...values,
			...newPagination,
		}
		const res = await getClueList(values)
		if (res?.success) {
			setTotal(res.data?.pageData?.total || 0)
			if (res.data?.pageData?.records) {
				setTableList(res.data?.pageData?.records || [])
				setCount(res.data?.statusCount)
			}
		}
		setLoading(false)
	}

	const getCitysFun = () => {
		getAllCitys().then((res: any) => {
			if (res?.success) {
				setCitysList(() => res.data || [])
			}
		})
	}

	const getSubjectFun = () => {
		getSubjectCompany().then((res: any) => {
			if (res.success && res.data?.success) {
				setSubjectList(res.data.data)
			}
		})
	}

	useEffect(() => {
		getTabelValue(formData)
		getCitysFun()
		getSubjectFun()
	}, [])

	const formItems = [
		{
			type: 'group',
			key: 'group1',
			groupItems: [
				{
					type: 'input',
					label: '姓名',
					name: 'username',
					key: 'username',
				},
				{
					type: 'input',
					label: '手机号',
					name: 'phone',
					key: 'phone',
				},
				// {
				// 	type: 'select',
				// 	label: '状态',
				// 	name: 'status',
				// 	key: 'status',
				// 	title: 'text',
				// 	items: Object.keys(statusC).map((item: string) => ({
				// 		value: item,
				// 		text: statusC[item],
				// 	})),
				// },
				{
					type: 'dateRange',
					label: '创建时间',
					name: 'date',
					key: 'date',
				},
			],
		},
		{
			type: 'group',
			key: 'group2',
			groupItems: [
				{
					type: 'input',
					label: ' 创建人',
					name: 'createUserName',
					key: 'createUserName',
				},
				{
					type: 'dateRange',
					label: '分配时间',
					name: 'allotDate',
					key: 'allotDate',
				},
				{
					type: 'input',
					label: ' 跟进人',
					name: 'followUserName',
					key: 'followUserName',
				},
			],
		},
		{
			type: 'group',
			key: 'group3',
			groupItems: [
				{
					type: 'select',
					label: '主体',
					name: 'subject',
					key: 'subject',
					title: 'text',
					items: subjectList?.map((item: any) => ({
						value: item.id,
						text: item.merchantName,
					})),
				},
				{
					type: 'cascader',
					label: '城市',
					name: 'cityId',
					key: 'cityId',
					placeholder: '请选择',
					items: citysList,
					fieldNames: {
						label: 'name',
						value: 'id',
						children: 'cityInfoList',
					},
				},
				{},
			],
		},
	]

	const openDetail = (record: Record<string, string>) => {
		history.push({
			pathname: '/merchantCenter/clue/detail',
			query: {
				pageType: PageType.Detail,
				id: record.id,
			},
		})
	}

	const openEditPage = (record: Record<string, string>) => {
		history.push({
			pathname: '/merchantCenter/clue/edit',
			query: {
				pageType: PageType.Edit,
				id: record.id,
			},
		})
	}

	const onDelete = async (ids: string) => {
		const res = await clueRemove(ids)
		if (res.success) {
			message.success('删除成功')
			getTabelValue(formData, params)
		}
	}

	const openClue = (va?: any) => {
		if (va) {
			setSelectedRowKeys([va.id])
		}
		const newSelectData1 = va ? [va] : [...selectData]
		const newSelectData2 = va ? [va] : [...selectData]
		if (newSelectData1?.length) {
			newSelectData1?.some((item: any) => {
				const newData = newSelectData2?.find(
					(items: any) =>
						item?.subject !== items?.subject ||
						item?.orgId !== items?.orgId ||
						item?.cityId !== items?.cityId,
				)
				if (newData) {
					message.warning(
						'只能批量分配同一主体，同一公司，同一城市的线索',
					)
					return true
				}
				if (va) {
					getFleeNames(va)
				} else {
					getFleeNames()
				}

				setVisible(true)
				return false
			})
		} else {
			message.warning('请选择要分配的线索')
		}
	}

	const onFinish = (values: any) => {
		getTabelValue(values)
		setFormItem(values)
		// eslint-disable-next-line no-param-reassign
	}

	// 搜索重置
	const onReset = () => {
		getTabelValue({})
	}

	const paginationChange = (current: number, size: number) => {
		getTabelValue(formData, {
			current,
			size,
		})
	}

	const rowSelection: any = {
		selectedRowKeys,
		onChange: onSelectChange,
	}

	const onSave = async () => {
		try {
			const FormD = await form.validateFields()
			if (FormD.userId) {
				const res = await clueAllot({
					clueId: selectedRowKeys.join(','),
					uid: FormD.userId,
				})
				if (res.success) {
					form.setFieldValue('userId', '')
					setSelectedRowKeys([])
					getTabelValue(formData, params)
					setVisible(false)
					setSelectData([])
				}
			} else {
				message.error('请选择跟进人')
			}
		} catch (error) {
			/* empty */
		}
	}

	const Colunms: any[] = useMemo(
		() => [
			...ClueColumns,
			{
				title: '操作',
				width: 350,
				align: 'center',
				fixed: 'right',
				render: (ffield: string, record: Record<string, any>) => (
					<Space size={12}>
						<Permissions permissionID="amc_merchantCenter_clue_detial">
							<Button
								type="link"
								onClick={() => openDetail(record)}>
								详情
							</Button>
						</Permissions>
						{record?.status !== 6 && (
							<Permissions permissionID="amc_merchantCenter_clue_edit">
								<Button
									type="link"
									onClick={() => openEditPage(record)}>
									编辑
								</Button>
							</Permissions>
						)}
						{record?.status < 3 && (
							<Permissions permissionID="amc_merchantCenter_clue_del">
								<Popconfirm
									placement="topLeft"
									title="你确定要删除这条线索数据吗？"
									onConfirm={() => onDelete(record.id)}
									okText="确定"
									cancelText="取消">
									<Button type="link" size="small">
										删除
									</Button>
								</Popconfirm>
							</Permissions>
						)}
						{record?.status !== 6 && (
							<Permissions permissionID="amc_merchantCenter_clue_allocation">
								<Button
									type="link"
									onClick={() => openClue(record)}>
									线索分配
								</Button>
							</Permissions>
						)}
						{record?.status !== 1 && (
							<Permissions permissionID="amc_merchantCenter_clue_record">
								<Button
									type="link"
									onClick={() => {
										setAccordingToRecordsId(record.id)
										setVisiblegj(true)
									}}>
									跟进记录
								</Button>
							</Permissions>
						)}
						{record?.status !== 6 && (
							<Button
								type="link"
								onClick={() => {
									history.push({
										pathname: '/order/add',
										query: {
											id: record.id,
											orgID: record.orgId,
											orgName: record.orgName,
										},
									})
								}}>
								线索下单
							</Button>
						)}
					</Space>
				),
			},
		],
		[],
	)
	const sunChange = (value: any) => {
		if (value) {
			setImportExcl(false)
		}
	}
	const data: any = {
		scroll: {x: 1200, y: 480},
	}

	return (
		<div className={Styles.list}>
			<div className={Styles.searchBox}>
				<SearchForm
					formLayout={{
						labelCol: {flex: '90px'},
						wrapperCol: {flex: '1'},
					}}
					formItems={formItems}
					onFinish={onFinish}
					onReset={onReset}
				/>
				<div className={Styles.tag}>
					<Radio.Group
						value={tabValue}
						onChange={(e) => {
							setTabValue(e.target.value)
							getTabelValue({...formData, status: e.target.value})
						}}>
						<Radio.Button value="">
							全部{count['0'] || 0}
						</Radio.Button>
						<Radio.Button value="1">
							初次未分配{count['1'] || 0}
						</Radio.Button>
						<Radio.Button value="2">
							已分配未触达{count['2'] || 0}
						</Radio.Button>
						<Radio.Button value="3">
							首轮已触达{count['3'] || 0}
						</Radio.Button>
						<Radio.Button value="4">
							非首轮已触达{count['4'] || 0}
						</Radio.Button>
						<Radio.Button value="5">
							已邀约到店{count['5'] || 0}
						</Radio.Button>
						<Radio.Button value="6">
							已转化成交{count['6'] || 0}
						</Radio.Button>
						<Radio.Button value="7">
							已战败/无意向{count['7'] || 0}
						</Radio.Button>
						<Radio.Button value="8">
							未分配（轮换进公海）{count['8'] || 0}
						</Radio.Button>
					</Radio.Group>
				</div>
			</div>
			<div className={Styles.content}>
				<div className={Styles.btnListBox}>
					<div>
						<Space size={12}>
							<Permissions permissionID="amc_merchantCenter_clue_add">
								<Button
									onClick={() => {
										history.push('/merchantCenter/clue/add')
									}}
									icon={<PlusOutlined />}
									type="primary"
									ghost
									size="small">
									新增
								</Button>
							</Permissions>
							<Permissions permissionID="amc_merchantCenter_clue_allocation">
								<Button
									onClick={() => openClue()}
									type="primary"
									size="small">
									线索分配
								</Button>
							</Permissions>
							<Permissions permissionID="amc_merchantCenter_clue_import">
								<Button
									icon={<ArrowUpOutlined />}
									className={Styles.warning}
									ghost
									size="small"
									onClick={() => {
										setImportExcl(true)
									}}>
									导入
								</Button>
							</Permissions>
							<Permissions permissionID="amc_merchantCenter_clue_export">
								<Button
									icon={<ArrowDownOutlined />}
									className={Styles.import}
									ghost
									size="small"
									onClick={() => {
										downloadDocumentUrl({
											resourceId: '171',
											queryDesc:
												'线索列表列表导出,resourceId:171',
											queryParam: formItem,
										})
									}}>
									导出
								</Button>
							</Permissions>
						</Space>
					</div>
				</div>
				{/* <CustomTable
            params={params}
            columns={Colunms}
            total={total}
            pagination
            callback={(paginations: any) => {
              getTabelValue(formData,paginations);
            }}
            loading={loading}
            dataSource={tableList}
          /> */}
				<Table
					columns={Colunms}
					dataSource={tableList}
					pagination={false}
					rowKey={(rocode: any) => rocode?.id}
					rowSelection={rowSelection}
					loading={loading}
					{...data}
				/>
				<div
					style={{
						paddingTop: '12px',
						display: 'flex',
						justifyContent: 'end',
					}}>
					<Pagination
						className={Styles.pagination}
						defaultCurrent={1}
						current={params.current}
						total={total}
						// eslint-disable-next-line no-shadow
						showTotal={(total, range) =>
							`第  ${range[0]} - ${range[1]} 条 / 总共 ${total} 条`
						}
						showSizeChanger
						showQuickJumper
						onChange={paginationChange}
					/>
				</div>
			</div>
			{visible ? (
				<Modal
					title="分配线索跟进BD"
					open={visible}
					forceRender
					onCancel={() => {
						setVisible(false)
						setSelectedRowKeys([])
						form.setFieldValue('userId', '')
						setSelectData([])
					}}
					width={500}
					onOk={onSave}>
					<Form
						layout="horizontal"
						labelCol={{flex: '140px'}}
						labelAlign="right"
						labelWrap
						autoComplete="off"
						name="PersonalInformationFom"
						form={form}>
						<FormSelect
							filterOption
							label="线索跟进BD"
							name="userId"
							placeholder="请选择线索跟进BD"
							items={fleename}
							keys="id"
							title="ditchName"
							rules={[{required: true}]}
						/>
					</Form>
				</Modal>
			) : (
				<></>
			)}

			<Modal
				title="跟进记录"
				open={visiblegj}
				onCancel={() => {
					setVisiblegj(false)
				}}
				footer={null}
				width={1000}
				onOk={() => {
					setVisiblegj(false)
				}}>
				<AccordingToRecordsOld
					clueId={accordingToRecordsId}
					keysObj={keysObj}
				/>
			</Modal>
			<ExportExcl
				info={importExcl}
				sunchange={sunChange}
				getData={getTabelValue}
			/>
		</div>
	)
}
